package tuanda.soict.firstsun.PresentationPackage;

import tuanda.soict.firstsun.ClickListenerPackage.*;
import tuanda.soict.firstsun.DataPackage.*;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.ClickListener;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.List;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.SelectionListener;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.Table;

public class StartScreen extends AbstractScreen {

	private Table table;
	private Texture imageBackground;
	private TextButton[] groupPlayer, groupSide, groupIncome, groupType;
	private Label notice;
	private int noticeID;
	private int numberOfGroup;
	private int skirmishIndex;

	public StartScreen(Object[] inputData, TalesOfTroubadour game) {
		super(inputData, game);
		table = new Table(skin);
		table.right().center().setFillParent(true);
		imageBackground = new Texture(Gdx.files.internal("Images/Start.jpg"));
		imageBackground.setFilter(TextureFilter.Linear, TextureFilter.Linear);
		createStartScreen();
	}

	public void dispose() {
		super.dispose();
	}

	@Override
	public void resize(int width, int height) {
		super.resize(width, height);
		stage.setViewport(width, height, true);
	}

	@Override
	public void render(float delta) {
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		stage.addActor(table);
		stage.draw();
	}

	public void clearState() {
		stage.clear();
		table.clear();
		stage.addActor(table);
	}

	public void createStartScreen() {
		clearState();
		table.defaults().right().top().minWidth(100).spaceBottom(5);
		Button startGameButton, optionsButton, helpButton, exitButton;
		startGameButton = new TextButton("Start", skin);
		startGameButton.setClickListener(new ClickListener() {
			@Override
			public void click(Actor actor, float x, float y) {
				createScenarioScreen();
			}
		});
		optionsButton = new TextButton("Settings", skin);
		helpButton = new TextButton("Help", getSkin());
		helpButton.setClickListener(new ClickListener() {
			@Override
			public void click(Actor actor, float x, float y) {
			}
		});
		exitButton = new TextButton("Exit", getSkin());
		exitButton.setClickListener(new ClickListener() {
			@Override
			public void click(Actor actor, float x, float y) {
				System.exit(0);
			}
		});
		table.setBackground(new NinePatch(imageBackground));
		table.add(startGameButton);
		table.row();
		//table.add(optionsButton);
		table.row();
		//table.add(helpButton);
		table.row();
		table.add(exitButton);
	}

	public void createScenarioScreen() {
		clearState();
		table.defaults().right().top().minWidth(100).spaceBottom(5);
		Button tutorialButton = new TextButton("Tutorial", skin);
		tutorialButton.setClickListener(new ClickListener() {
			@Override
			public void click(Actor actor, float x, float y) {
				Object[] testInputData = { "Spring", "Map/Campaign/Level_1",
						"Map/Campaign/Level_1/level.txt", true,
						"TileSets/Spring/level.txt", null };
				myGame.setScreen(new TiledMapRendererScreen(testInputData,
						myGame));
			}
		});
		Button campaignButton = new TextButton("Campaign", skin);
		Button skirmishButton = new TextButton("Skirmish", skin);
		skirmishButton.setClickListener(new ClickListener() {
			@Override
			public void click(Actor actor, float x, float y) {
				createSkirmishScreen();
			}
		});
		Button backButton = new TextButton("Back", skin);
		backButton.setClickListener(new ClickListener() {
			@Override
			public void click(Actor actor, float x, float y) {
				createStartScreen();
			}
		});

		table.setBackground(new NinePatch(imageBackground));
		table.add(tutorialButton);
		table.row();
		//table.add(campaignButton);
		table.row();
		table.add(skirmishButton);
		table.row();
		table.add(backButton);
	}

	public void createSkirmishScreen() {
		clearState();
		table.defaults().center().bottom().minWidth(Gdx.graphics.getWidth())
				.spaceBottom(5);
		String data = Gdx.files
				.internal("Map/Skirmish/SkirmishDescription.txt").readString();
		int i, j;
		i = data.indexOf(":");
		j = data.indexOf(";");
		int numberSkirmish = Integer.parseInt(data.substring(i + 1, j));
		Object[] skirmishList = new Object[numberSkirmish];

		for (int k = 0; k < numberSkirmish; k++) {
			i = data.indexOf(",", i + 1);
			j = data.indexOf(";", j + 1);
			skirmishList[k] = data.substring(i + 1, j);
		}
		List list = new List(skin);
		ScrollPane scrollPane = new ScrollPane(list, skin);
		list.setItems(skirmishList);
		list.setSelectionListener(new SelectionListener() {

			@Override
			public void selected(Actor actor, int index, String value) {
				createSkirmishSettingScreen(index);
			}
		});
		table.add(scrollPane).fillX();
	}

	public void createSkirmishSettingScreen(int index) {
		clearState();
		table.defaults().center().bottom().minWidth(70)
				.spaceLeft(5 + (Gdx.graphics.getWidth() - 320) >> 4)
				.spaceBottom(5);
		String data = Gdx.files.internal(
				"Map/Skirmish/" + (index + 1) + "/level.txt").readString();
		int numberGroup = Integer.parseInt(data.substring(
				data.indexOf(":") + 1, data.indexOf(";")));
		numberOfGroup = numberGroup;
		skirmishIndex = index;

		groupPlayer = new TextButton[numberGroup];

		groupSide = new TextButton[numberGroup];

		groupIncome = new TextButton[numberGroup];

		groupType = new TextButton[numberGroup];

		Object[] sides = new Object[numberGroup];
		for (int i = 0; i < numberGroup; i++) {
			sides[i] = i;
		}

		table.setBackground(new NinePatch(imageBackground));
		table.add(new Label("Name", skin));
		table.add(new Label("Income", skin));
		table.add(new Label("Side", skin));
		table.add(new Label("Type", skin));
		table.row();

		for (int i = 0; i < numberGroup; i++) {

			groupPlayer[i] = new TextButton("PLAYER", skin);
			groupPlayer[i].setClickListener(new ChangePlayerClickListener(3,
					groupPlayer[i]));

			groupIncome[i] = new TextButton("500", skin);
			groupIncome[i].setClickListener(new ChangeIncomeClickListener(2500,
					groupIncome[i]));

			groupSide[i] = new TextButton("" + i, skin);
			groupSide[i].setClickListener(new ChangeSideClickListener(
					numberGroup, groupSide[i]));

			groupType[i] = new TextButton("HUMAN", skin);
			groupType[i].setClickListener(new ChangeTypeClickListener(2,
					groupType[i]));

			table.add(groupPlayer[i]);
			table.add(groupIncome[i]);
			table.add(groupSide[i]);
			table.add(groupType[i]);
			table.row();
		}

		notice = new Label("", skin);
		TextButton backButton = new TextButton("BACK", skin);
		backButton.setClickListener(new ClickListener() {

			@Override
			public void click(Actor actor, float x, float y) {
				createSkirmishScreen();
			}
		});
		TextButton nextButton = new TextButton("NEXT", skin);
		nextButton.setClickListener(new ClickListener() {

			@Override
			public void click(Actor actor, float x, float y) {
				GroupDataStructure data = createGroupDataStructure();
				if (data != null) {
					Object[] testInputData = {
							"Spring",
							"Map/Skirmish/" + (skirmishIndex + 1),
							"Map/Skirmish/" + (skirmishIndex + 1)
									+ "/level.txt", false,
							"TileSets/Spring/level.txt", data };
					myGame.setScreen(new TiledMapRendererScreen(testInputData,
							myGame));
				} else {
					notice.setText("Error Code: " + noticeID);
				}
			}
		});
		table.add(backButton).width(70);
		table.add(notice).colspan(2);
		table.add(nextButton).width(70);
	}

	public GroupDataStructure createGroupDataStructure() {
		GroupDataStructure result;
		String[] name = new String[numberOfGroup];
		int[] income = new int[numberOfGroup];
		int[] side = new int[numberOfGroup];
		int[] type = new int[numberOfGroup];
		int[] playerType = new int[numberOfGroup];
		String temp;

		noticeID = 0;

		for (int i = 0; i < numberOfGroup; i++) {
			temp = groupPlayer[i].getText().toString();

			if (temp.equalsIgnoreCase("NONE") == false) {
				if (temp.equalsIgnoreCase("PLAYER")) {
					playerType[i] = CommonConstants.HUMAN_PLAYER;
				} else {// (temp.equalsIgnoreCase("COMP"))
					playerType[i] = CommonConstants.COMPUTER_PLAYER;
				}

				name[i] = ScenarioConstants.groupName[i];
				income[i] = Integer.parseInt(groupIncome[i].getText()
						.toString());
				side[i] = Integer.parseInt(groupSide[i].getText().toString());

				temp = groupType[i].getText().toString();
				if (temp == "HUMAN") {
					type[i] = 0;
				} else // if (temp == "ELF")
				{
					type[i] = 1;
				}
			}
		}

		boolean playerCheck = false;
		int numberGroup = 0;
		int currentSide, lastSide = -1;
		boolean sideCheck = false;

		for (int i = 0; i < numberOfGroup; i++) {
			if (name[i] != null) {
				numberGroup++;

				currentSide = side[i];

				if (lastSide != -1) {
					if (currentSide != lastSide) {
						sideCheck = true;
					}
				} else {
					lastSide = currentSide;
				}

				if (playerType[i] == CommonConstants.HUMAN_PLAYER) {
					playerCheck = true;
				}
			}
		}

		if (numberGroup < 2) {
			noticeID = ScenarioConstants.NOT_ENOUGH_GROUP;
			return null;
		}

		if (playerCheck == false) {
			noticeID = ScenarioConstants.NOT_ENOUGH_PLAYER;
			return null;
		}

		if (sideCheck == false) {
			noticeID = ScenarioConstants.NOT_ENOUGH_SIDE;
			return null;
		}

		result = new GroupDataStructure(name, income, side, type, playerType);
		return result;
	}
}
